package com.ruoyi.common.utils;

import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @创建者：zhouwei
 * @创建时间：2022/7/23
 * @描述：
 */
public class WordToPDF {
	public static void main(String[] args) {
		//实例化Document类的对象
//		Document doc = new Document();
//
//		//加载Word
//		doc.loadFromFile("D:/webdata/yd/file/202209/物业费收据1663141760057.docx");
		try {
			String ss =  wordConverterToPdf("D:\\webdata\\yd\\file\\202209\\物业费收据1663141760057.docx");
			System.out.println("ss: " + ss);
		} catch (IOException e) {
			e.printStackTrace();
		}
//
//		//保存为PDF格式
//		doc.saveToFile("D:/WordToPDF.pdf",FileFormat.PDF);
//		List<String> list = getDataPDF("D:/","D:/物业费收据_1658561016034.docx");
//		String out = wordToPdf("D:/物业费收据_1658561016034.docx","D:/");
//		wordConverterToPdf();
		System.out.println();
	}

	public static String wordConverterToPdf(String docxPath) throws IOException {
		File file = new File(docxPath);
		if(file.exists()){
			System.out.println("文件存在");
		}else{
			System.out.println("文件不存在");
		}
		String path = file.getParent();
		String filePath = "";
		try {
			String osName = System.getProperty("os.name");
			String command = "";
			filePath = path + File.separator + file.getName().replaceAll(".(?i)docx", ".pdf");
			if (osName.contains("Windows")) {
				//soffice --convert-to pdf  -outdir E:/test.docx
				command = "soffice --convert-to pdf  -outdir " + path + " " + docxPath;
			} else {
				command = "doc2pdf --output=" + path + File.separator + file.getName().replaceAll(".(?i)docx", ".pdf") + " " + docxPath;
			}
			//doc2pdf --output=/home/ydimg/file/202209/物业费收据_1663143740089.pdf  /home/ydimg/file/202209/物业费收据_1663143740089.docx
			System.out.println("command :" + command);
			String result = CommandExecute.executeCommand(command);
//	        LOGGER.info("result==" + result);
			System.out.println("生成pdf的result==" + result);
			if (result.equals("") || result.contains("writer_pdf_Export")) {
				return filePath;
			}
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}
		return filePath;
	}

	public static String wordToPdf(String filePath, String cachePath) {
		FileInputStream fileInputStream = null;
		FileOutputStream  fileOutputStream = null;
		try {
			File file = new File(filePath);
			// 读取docx文件
			fileInputStream = new FileInputStream(file);
			XWPFDocument xwpfDocument = new XWPFDocument(fileInputStream);
			PdfOptions pdfOptions = PdfOptions.create();
			// 输出路径
			String outPath = cachePath + File.separator + file.getName() + ".pdf";
			fileOutputStream = new FileOutputStream(outPath);
			// 调用转换
			PdfConverter.getInstance().convert(xwpfDocument,fileOutputStream,pdfOptions);
			fileInputStream.close();
			fileOutputStream.close();
			return outPath;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String pdfFileToImages(String filePath, String profile,String cachePath,String orderNo) {
		String imgPath = "";
		try {
			PDDocument pd = PDDocument.load(new File(filePath));
			PDFRenderer pdfRenderer = new PDFRenderer(pd);
			for (int page = 0; page < pd.getNumberOfPages(); ++page) {
				String imgUrl = cachePath + orderNo +"_" + page + ".jpg";
				BufferedImage image = pdfRenderer.renderImageWithDPI(page, 96, ImageType.RGB);
				//将图片数据保存为PNG格式文档
				File file = new File(profile + File.separator + imgUrl);

				int width = image.getWidth();
				int height = image.getHeight();
				image = ImageCropUtils.cropImage(image,0,0,width,(int) (height / 1.7));
				ImageIO.write(image, "jpg", file);
				System.out.println(file.getAbsolutePath());
				imgPath = imgUrl;

				InputStream inputStream = new FileInputStream(new File(profile + File.separator + imgUrl));
				OssUtil.uploadObs(inputStream, DateUtils.getMonthStr(new Date()) + File.separator + orderNo +"_" + page + ".png",15);
			}
			pd.close();
		}  catch (Exception e) {
			e.printStackTrace();
		}
		return imgPath;
	}

	//PDF转图⽚（帮助⽂档）

	/**
	 *   windows  系统下 word 转 pdf  然后转图片
	 * @param imagePath
	 * @param fileName
	 * @return
	 */
	public static List<String> getDataPDF(String imagePath,String fileName) {
		File newFile = new File(fileName);
		if (!newFile.exists()) {
			newFile.mkdirs();
		}
		List<String> strList = new ArrayList<>();
		try {
			//word转PDF   pdf⽂件名
			String pdfName = newFile.getName().substring(0, newFile.getName().lastIndexOf(".")) + ".pdf";
			File outputFile = new File(imagePath + pdfName);
			InputStream doc = new FileInputStream(newFile);

			OutputStream outputStream = new FileOutputStream(outputFile);
			IConverter converter = LocalConverter.builder().build();
			converter.convert(doc).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
			outputStream.close();
			outputStream.flush();
			//PDF转图⽚
			List<String> imageList = PDFImges(imagePath + pdfName, imagePath);
			for (String str : imageList) {
				strList.add(imagePath + str);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return strList;
	}
	/**
	 * PDF转图⽚
	 *
	 * @param
	 * @return null
	 * @Author HB
	 * @Date 2021/4/13 09:56
	 **/
	public static List<String> PDFImges(String pdfPath, String imagePath) {
		List<String> imageList = new ArrayList<>();
		Document document = new Document();
		try {
			document.setFile(pdfPath);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		//缩放⽐例
		float scale = 2.5f;
		//旋转⾓度
		float rotation = 0f;
		for (int i = 0; i < document.getNumberOfPages(); i++) {
			BufferedImage image = null;
			try {
				image = (BufferedImage)document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, scale);
				RenderedImage rendImage = image;
				try {
					int a = i + 100;
					File file = new File(imagePath + "/help_" + a + ".jpg");
					ImageIO.write(rendImage, "jpg", file);
					imageList.add(file.getName());
				} catch (IOException e) {
					e.printStackTrace();
				}
				image.flush();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			document.dispose();
		}
		return imageList;
	}
}
